package models

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	DB  *gorm.DB
	err error
)

func MysqlInit() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./conf")

	err = viper.ReadInConfig()
	if err != nil {
		fmt.Println("文件读取失败")
	}
	username := viper.GetString("mysql.User")
	password := viper.GetString("mysql.password")
	host := viper.GetString("mysql.Host")
	port := viper.GetString("mysql.Port")
	database := viper.GetString("mysql.Database")

	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		username,
		password,
		host,
		port,
		database)
	fmt.Println(dsn)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败")
		return
	} else {
		fmt.Println("数据库连接成功")
	}
}
